const { Op } = require("sequelize");

const Employee = require('../model/employee.model')

const ProjectEmp = require('../model/projectEmp.model')

const queryUtil = async (pageNum, pageSize, whereOpt, model) => {
    const offset = (pageNum - 1) * pageSize
    const limit = pageSize * 1
    // console.log(whereOpt);
    const { count, rows } = await model.findAndCountAll({
        where: whereOpt,
        offset,
        limit
    })
    // console.log(rows);
    return {
        pageNum,
        pageSize,
        total: count,
        list: rows,
    }
}

const parseUtil = async (list) => {
    await Promise.all(list.map(
        async (project) => {
            project.dataValues.directorName = (await Employee.findOne({ attributes: ['empName'], where: { id: project.director } })).dataValues.empName
            const empIdList = await ProjectEmp.findAll({
                attributes: ['empId'],
                where: { projectId: project.dataValues.id }
            })
            let empIds = []

            empIdList.map((emp) => {
                empIds.push(emp.dataValues.empId)
            })
            const empNames = []
            const empNameList = await Employee.findAll({ attributes: ['empName'], where: { id: empIds } })

            empNameList.map((emp) => {
                empNames.push(emp.dataValues.empName)
            })
            // console.log(empNames);
            let employee = []
            for (let i = 0; i < empIds.length; i++) {
                employee.push({ 'id': empIds[i], 'empName': empNames[i] });
            }

            project.dataValues.employee = employee
        }
    ))
}

const dutyWhereUtil=(empId)=>{
    //今天的时间
    const start = new Date(new Date().toLocaleDateString()).getTime();
    console.log(start);
    // //明天的时间
    const end = new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1;
    console.log(end);

    const whereOpt = {
        empId, signInTime: {
            [Op.between]: [start, end]
        }
    }
    return whereOpt
}

module.exports = {
    queryUtil,
    parseUtil,
    dutyWhereUtil
}